using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.ComponentModel.Design;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Text;
using Microsoft.Practices.Common.Services;
using Microsoft.Practices.ComponentModel;
using Microsoft.Practices.RecipeFramework.Library.Actions;
using Microsoft.Practices.RecipeFramework.Services;
using Microsoft.VisualStudio.TextTemplating;
using PrismFactory.SoftwareFactory.Properties;
using Engine = EnvDTE80.Engine;

namespace PrismFactory.SoftwareFactory.Actions.Temp
{
    [ServiceDependency(typeof (ITypeResolutionService))]
    public abstract class T4Action : DynamicInputAction
    {
        // Methods

        protected string GetBasePath()
        {
            return base.GetService<IConfigurationService>(true).BasePath;
        }

        protected string GetTemplateBasePath()
        {
            return new DirectoryInfo(GetBasePath() + @"\Templates").FullName;
        }

        protected string Render(string templateCode, string templateFile)
        {
            string basePath = GetBasePath();
            ITextTemplatingEngine engine = new Microsoft.VisualStudio.TextTemplating.Engine();
            var service = (IValueInfoService) GetService(typeof (IValueInfoService));
            var arguments = new Dictionary<string, PropertyData>();
            foreach (string str2 in base.additionalArguments.Keys)
            {
                Type type = null;
                try
                {
                    type = service.GetInfo(str2).Type;
                }
                catch (ArgumentException)
                {
                    if (base.additionalArguments[str2] != null)
                    {
                        type = base.additionalArguments[str2].GetType();
                    }
                    else
                    {
                        continue;
                    }
                }
                var data = new PropertyData(base.additionalArguments[str2], type);
                arguments.Add(str2, data);
            }
            var host = new TemplateHost(basePath, arguments);
            host.TemplateFile = templateFile;
            string str3 = engine.ProcessTemplate(templateCode, host);
            if (host.Errors.HasErrors)
            {
                throw new TemplateException(host.Errors);
            }
            if (host.Errors.HasWarnings)
            {
                var builder = new StringBuilder();
                foreach (CompilerError error in host.Errors)
                {
                    builder.AppendLine(error.ToString());
                }
                Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "T4Action_CompilationWarnings", new object[] {templateFile, builder.ToString()}));
            }
            return str3;
        }
    }
}